module LibTrafmonitor

    require 'yaml'
    require 'logger'
    
    class Config
        # Config#new creates new configuration object. Takes
        # path to configuration file (including the file) as an argument.
        def initialize( path )
            @path   = path
            @config = open( path ) { |f| YAML.load f }
        end

        # Returns value of 'logfile' configuration variable.
        def logfile
            @config[ 'logfile' ]
        end

        # Returns value of 'pidfile' configuration variable.
        def pidfile
            @config[ 'pidfile' ]
        end

        # Returns value of 'filter' configuration variable.
        def filter
            @config[ 'filter' ]
        end
    end

    class Stats
        @@div_kilobytes = 1024
        @@div_megabytes = 1048600
        @@div_gigabytes = 0.00097656

        # Creates new Stats object.
        def initialize
            @stats            = Hash.new
            @time_initialized = Time.now

            $LOG.info do 'Statistics initialized' end
        end

        # Resets internal counters of Stats object.
        def reset
            @stats            = Hash.new
            @time_initialized = Time.now

            $LOG.info do 'Statistics reset' end
        end

        # Returns Float number of seconds since Stats object was (re)initialized.
        def time_running
            Time.now - @time_initialized
        end

        # Accounts bytes of data fetched by IP address.
        def account( ip_dst, bytes )
            @ip_dst = ip_dst
            @bytes  = bytes
            @stats[ @ip_dst ] = @stats.fetch( @ip_dst, 0 ) + bytes
        end

        def to_s
            raise 'Not implemented'
        end

        # Dumps per IP statistics to logfile.
        def to_log
            $LOG.info do 'Statistics for ' + self.time_running.to_s + ' seconds.' end

            @stats.each { |key,value|
                $LOG.info do "#{key} #{value.to_f / @@div_megabytes}" end
            }
        end

        def to_csv
            raise 'Not implemented'
        end

        def to_yaml
            raise 'Not implemented'
        end
    end

end # module trafmonitor
